package com.app.common.utils;



import com.app.common.vo.FileInfo;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class FileUtil {


    protected final static Logger logger = LoggerFactory.getLogger(FileUtil.class);


    private static MimetypesFileTypeMap mimetypesFileTypeMap;


    /**
     * 下载http文件流
     *
     * @param urlStr
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadHttpFile(String urlStr, HttpServletRequest request, HttpServletResponse response, String fileName) {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //得到输入流
            inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = FileUtil.inputStreamToByte(inputStream);
            // 下载
            out = response.getOutputStream();
            long contentLength = getData.length;
            FileUtil.setResponse(fileName, contentLength, request, response);
            out.write(getData);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("下载失败!");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //File、FileInputStream 转换为byte数组
    public static byte[] inputStreamToByte(InputStream inputStream) {
        try {
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("文件转换失败!");
        }
    }

    /**
     * 下载文件流
     *
     * @param file
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadFile(File file, HttpServletRequest request, HttpServletResponse response, String fileName) {
        if (file != null && file.exists() && file.length() > 0L) {
            try {
                RandomAccessFile randomFile = new RandomAccessFile(file, "r");
                Throwable var5 = null;

                Object var54;
                try {
                    ServletOutputStream out = response.getOutputStream();
                    Throwable var7 = null;

                    try {
                        long contentLength = randomFile.length();
                        String range = request.getHeader("Range");
                        long start = 0L;
                        long end = 0L;
                        if (range != null && range.startsWith("bytes=")) {
                            String[] values = range.split("=")[1].split("-");
                            start = Long.parseLong(values[0]);
                            if (values.length > 1) {
                                end = Long.parseLong(values[1]);
                            }
                        }

                        int requestSize;
                        if (end != 0L && end > start) {
                            requestSize = Long.valueOf(end - start + 1L).intValue();
                        } else {
                            requestSize = 2147483647;
                        }

                        FileUtil.setResponse(fileName, contentLength, request, response);

                        randomFile.seek(start);

                        byte[] buffer;
                        for (int needSize = requestSize; needSize > 0; needSize -= buffer.length) {
                            buffer = new byte[1024];
                            int len = randomFile.read(buffer);
                            if (needSize < buffer.length) {
                                out.write(buffer, 0, needSize);
                            } else {
                                out.write(buffer, 0, len);
                                if (len < buffer.length) {
                                    break;
                                }
                            }
                        }

                        out.flush();
                        var54 = null;
                    } catch (Throwable var47) {
                        var7 = var47;
                        throw var47;
                    } finally {
                        if (out != null) {
                            if (var7 != null) {
                                try {
                                    out.close();
                                } catch (Throwable var46) {
                                    var7.addSuppressed(var46);
                                }
                            } else {
                                out.close();
                            }
                        }

                    }
                } catch (Throwable var49) {
                    var5 = var49;
                    throw var49;
                } finally {
                    if (randomFile != null) {
                        if (var5 != null) {
                            try {
                                randomFile.close();
                            } catch (Throwable var45) {
                                var5.addSuppressed(var45);
                            }
                        } else {
                            randomFile.close();
                        }
                    }

                }
            } catch (IOException var51) {
                logger.debug(var51.getMessage(), var51);
                throw new RuntimeException(var51.getMessage());
            }
        } else {
            throw new RuntimeException("文件为空或不存在！");
        }
    }

    /**
     * @param fileName
     * @param contentLength
     * @param request
     * @param response
     * @return
     */
    public static void setResponse(String fileName, long contentLength, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(FileUtil.getContentType("0.jpg"));
            boolean isPreview = "preview".equalsIgnoreCase(request.getParameter("source"));
            response.addHeader("Content-Disposition", (!isPreview ? "attachment; " : "") + "filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Accept-Ranges", "bytes");

            String range = request.getHeader("Range");
            if (range == null) {
                response.setHeader("Content-Length", String.valueOf(contentLength));
            } else {
                response.setStatus(206);
                long requestStart = 0L;
                long requestEnd = 0L;
                String[] ranges = range.split("=");
                if (ranges.length > 1) {
                    String[] rangeDatas = ranges[1].split("-");
                    requestStart = Long.parseLong(rangeDatas[0]);
                    if (rangeDatas.length > 1) {
                        requestEnd = Long.parseLong(rangeDatas[1]);
                    }
                }

                long length = 0L;
                if (requestEnd > 0L) {
                    length = requestEnd - requestStart + 1L;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);
                } else {
                    length = contentLength - requestStart;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + (contentLength - 1L) + "/" + contentLength);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("response响应失败!");
        }
    }

    public static String getContentType(String fileName) {
        if (mimetypesFileTypeMap == null) {
            mimetypesFileTypeMap = new MimetypesFileTypeMap();
        }

        return mimetypesFileTypeMap.getContentType(fileName);
    }

    /**
     * 将磁盘的多个文件打包成压缩包并输出流下载
     *
     * @param pathList
     * @param request
     * @param response
     */
    public static void zipDirFileToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置response参数并且获取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);

            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                File file = new File(map.get("path"));
                InputStream inputStream = new FileInputStream(file);
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将网络url资源文件的多个文件打包成压缩包并输出流下载
     *
     * @param pathList
     * @param request
     * @param response
     */
    public static void zipUrlToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置response参数并且获取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);

            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                InputStream inputStream = getInputStreamFromUrl(map.get("path"));
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static ZipArchiveOutputStream getServletOutputStream(HttpServletResponse response) throws Exception {

        String outputFileName = "文件" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream out = response.getOutputStream();

        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
        zous.setUseZip64(Zip64Mode.AsNeeded);
        return zous;
    }

    private static void setByteArrayOutputStream(String fileName, InputStream inputStream, ZipArchiveOutputStream zous) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] bytes = baos.toByteArray();

        //设置文件名
        ArchiveEntry entry = new ZipArchiveEntry(fileName);
        zous.putArchiveEntry(entry);
        zous.write(bytes);
        zous.closeArchiveEntry();
        baos.close();
    }

    /**
     * 通过网络地址获取文件InputStream
     *
     * @param path 地址
     * @return
     */
    private static InputStream getInputStreamFromUrl(String path) {
        URL url = null;
        InputStream is = null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }





    //zip打包下载
    public static void httpDownloadZipFile(String sourceFilePath, HttpServletResponse response, String zipName) throws IOException{

        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            throw new RuntimeException(sourceFilePath + "不存在！");
        }

        if(StringUtils.isBlank(zipName)){
            zipName = sourceFile.getName();
        }

        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8")+".zip");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream out = response.getOutputStream();
        compressFile(sourceFile, out);
        out.flush();
    }

    public static OutputStream compressFile(File sourceFile, OutputStream outputStream) throws IOException {
        try (CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
             ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)) {
             doCompressFile(sourceFile, zipOutputStream, StringUtils.EMPTY);
            return outputStream;
        }
    }

    private static void doCompressFile(File sourceFile, ZipOutputStream zipOutputStream, String zipFilePath) throws IOException {
        // 如果文件是隐藏的，不进行压缩
        if (sourceFile.isHidden()) {
            return;
        }
        if (sourceFile.isDirectory()) {//如果是文件夹
            handDirectory(sourceFile, zipOutputStream, zipFilePath);
        } else {//如果是文件就添加到压缩包中
            try (FileInputStream fileInputStream = new FileInputStream(sourceFile)) {
                String fileName = zipFilePath + sourceFile.getName();
                addCompressFile(fileInputStream, fileName, zipOutputStream);
            }
        }
    }

    /**
     * 处理文件夹
     *
     * @param dir         文件夹
     * @param zipOut      压缩包输出流
     * @param zipFilePath 压缩包中的文件夹路径
     * @throws IOException
     */
    private static void handDirectory(File dir, ZipOutputStream zipOut, String zipFilePath) throws IOException {
        File[] files = dir.listFiles();
        if (ArrayUtils.isEmpty(files)) {
            ZipEntry zipEntry = new ZipEntry(zipFilePath + dir.getName() + File.separator);
            zipOut.putNextEntry(zipEntry);
            zipOut.closeEntry();
            return;
        }
        for (File file : files) {
            doCompressFile(file, zipOut, zipFilePath + dir.getName() + File.separator);
        }
    }


    /**
     * 将单个文件写入文件压缩包
     *
     * @param inputStream     文件输入流
     * @param fileName        文件在压缩包中的相对全路径
     * @param zipOutputStream 压缩包输出流
     */
    private static void addCompressFile(InputStream inputStream, String fileName, ZipOutputStream zipOutputStream) {
        try {

            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = bufferedInputStream.read(bytes)) >= 0) {
                zipOutputStream.write(bytes, 0, length);
                zipOutputStream.flush();
            }
            zipOutputStream.closeEntry();
        } catch (Exception e) {
            logger.info("addFileToZip exception:", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 将文件打包到zip
     *
     * @param documentMap 需要下载的附件集合 map的key对应zip里的文件夹名
     * @return ByteArrayOutputStream
     */
    public static OutputStream compressZipFile(Map<String, List<FileInfo>> documentMap, OutputStream outputStream) {
        CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
        ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream);
        try {
            for (Map.Entry<String, List<FileInfo>> documentListEntry : documentMap.entrySet()) {
                String dirName = documentMap.size() > 1 ? documentListEntry.getKey() : "";
                Map<String, Integer> fileNameToLen = new HashMap<>();//记录单个合同号文件夹下每个文件名称出现的次数（对重复文件名重命名）
                for (FileInfo document : documentListEntry.getValue()) {
                    try {
                        //防止单个文件夹下文件名重复 对重复的文件进行重命名
                        String documentName = document.getFileName();
                        if (fileNameToLen.get(documentName) == null) {
                            fileNameToLen.put(documentName, 1);
                        } else {
                            int fileLen = fileNameToLen.get(documentName) + 1;
                            fileNameToLen.put(documentName, fileLen);
                            documentName = documentName + "(" + fileLen + ")";
                        }
                        String fileName = documentName + "." + document.getSuffix();
                        if (StringUtils.isNotBlank(dirName)) {
                            fileName = dirName + File.separator + fileName;
                        }
                        addCompressFile(document.getFileInputStream(), fileName, zipOutputStream);
                    } catch (Exception e) {
                        logger.info("filesToZip exception :", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("filesToZip exception:" + e.getMessage(), e);
        }
        return outputStream;
    }





    /**
     * 将文件打包到zip并创建文件
     *
     * @param sourceFilePath
     * @param zipFilePath
     * @param zipName
     * @throws IOException
     */
    public static void createLocalCompressFile(String sourceFilePath, String zipFilePath, String zipName) throws IOException {
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            throw new RuntimeException(sourceFilePath + "不存在！");
        }
        if(StringUtils.isBlank(zipName)){
            zipName = sourceFile.getName();
        }
        File zipFile = createNewFile(zipFilePath + File.separator + zipName + ".zip");
        try (FileOutputStream fileOutputStream = new FileOutputStream(zipFile)) {
            compressFile(sourceFile, fileOutputStream);
        }
    }

    /**
     * 检查文件名是否已经存在，如果存在，就在文件名后面加上“(1)”，如果文件名“(1)”也存在，则改为“(2)”，以此类推。如果文件名不存在，就直接创建一个新文件。
     *
     * @param filename 文件名
     * @return File
     */
    public static File createNewFile(String filename) {
        File file = new File(filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            String base = filename.substring(0, filename.lastIndexOf("."));
            String ext = filename.substring(filename.lastIndexOf("."));
            int i = 1;
            while (true) {
                String newFilename = base + "(" + i + ")" + ext;
                file = new File(newFilename);
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                i++;
            }
        }
        return file;
    }


    public static void main(String[] args) throws Exception {
        //在本地创建压缩文件
        FileUtil.createLocalCompressFile("D:\\picture", "D:\\test","code");
    }




}
